const { Service } = require('dx-router-admin');
const { OpendbVerifyCodes } = require('dx-func-entity');

module.exports = class VerifyCodes extends Service {
	constructor(ctx) {
		super(ctx);
		this.entity = OpendbVerifyCodes;
	}
	// 校验验证码
	async checkVerifyCode(mobile, code, scene = 'login') {
		if ((code + '').length != 6) {
			this.$dx.error('验证码错误');
		}
		let row = await this.where('mobile', mobile).where('scene', scene).where('code', code).find();
		if (!row) {
			this.$dx.error('验证码错误');
		}
		// 验证码过期
		if (row.expired_date < Date.now()) {
			this.$dx.error('验证码过期');
		}
		// 验证码已使用
		if (row.state === 1) {
			this.$dx.error('验证码已使用');
		}
		// 更新验证码状态
		await this.$dx.service.verifyCodes.save({ _id: row._id, state: 1 });
		return true;
	}
};
